from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
from datetime import datetime

router = APIRouter()


# 数据模型
class ProcessingTask(BaseModel):
    id: int
    title: str
    description: str
    status: str
    icon: str
    details: Dict[str, Any]


class TaskConfig(BaseModel):
    id: int
    title: str
    description: str
    icon: str
    status: str
    details: Dict[str, Any]


class ProcessingResponse(BaseModel):
    success: bool
    data: List[ProcessingTask]
    message: str
    timestamp: datetime


# Mock数据 - 处理任务配置
task_configs = {
    "knowledge": [
        {
            "id": 1,
            "title": "问题解析",
            "description": "分析用户问题的类型和需求",
            "icon": "fas fa-search",
            "status": "completed",
            "details": {
                "title": "问题解析完成",
                "items": [
                    "✓ 意图识别：环境监测专业知识查询",
                    "✓ 关键词提取：铜分析方法",
                    "✓ 难度评估：中等",
                    "✓ 输出格式：结构化回答"
                ]
            }
        },
        {
            "id": 2,
            "title": "知识检索",
            "description": "从知识库中检索相关信息",
            "icon": "fas fa-book",
            "status": "completed",
            "details": {
                "title": "知识检索完成",
                "items": [
                    "✓ 检索范围：个人知识库",
                    "✓ 匹配文档：3篇相关文档",
                    "✓ 相关度评分：85%",
                    "✓ 检索时间：0.23秒"
                ]
            }
        }
    ],
    "data": [
        {
            "id": 1,
            "title": "需求分析",
            "description": "分析数据查询需求",
            "icon": "fas fa-chart-line",
            "status": "completed",
            "details": {
                "title": "需求分析完成",
                "items": [
                    "✓ 分析目标：AQI趋势分析",
                    "✓ 时间范围：最近30天",
                    "✓ 空间范围：深圳市",
                    "✓ 指标要求：AQI指数"
                ]
            }
        },
        {
            "id": 2,
            "title": "SQL生成",
            "description": "生成数据查询SQL语句",
            "icon": "fas fa-database",
            "status": "completed",
            "details": {
                "title": "SQL生成完成",
                "items": [
                    "✓ 表名识别：air_quality_data",
                    "✓ 字段映射：date, aqi_value, station_name",
                    "✓ 条件构建：深圳地区，30天内",
                    "✓ 语法检查：通过"
                ]
            }
        },
        {
            "id": 3,
            "title": "数据查询",
            "description": "执行数据查询获取结果",
            "icon": "fas fa-table",
            "status": "completed",
            "details": {
                "title": "数据查询完成",
                "items": [
                    "✓ 数据源连接：成功",
                    "✓ 查询执行：成功",
                    "✓ 数据获取：30条记录",
                    "✓ 质量检查：通过"
                ]
            }
        },
        {
            "id": 4,
            "title": "数据处理",
            "description": "处理和分析查询结果",
            "icon": "fas fa-cogs",
            "status": "completed",
            "details": {
                "title": "数据处理完成",
                "items": [
                    "✓ 数据清洗：完成",
                    "✓ 异常值处理：完成",
                    "✓ 统计计算：完成",
                    "✓ 趋势分析：完成"
                ]
            }
        },
        {
            "id": 5,
            "title": "生成报告",
            "description": "生成分析报告和可视化",
            "icon": "fas fa-file-alt",
            "status": "completed",
            "details": {
                "title": "报告生成完成",
                "items": [
                    "✓ 图表生成：完成",
                    "✓ 统计分析：完成",
                    "✓ 结论生成：完成",
                    "✓ 报告格式：HTML"
                ]
            }
        }
    ],
    "image": [
        {
            "id": 1,
            "title": "图像识别",
            "description": "识别图像中的对象和特征",
            "icon": "fas fa-eye",
            "status": "completed",
            "details": {
                "title": "图像识别完成",
                "items": [
                    "✓ 图像格式验证：通过",
                    "✓ 对象识别：12个对象",
                    "✓ 特征提取：完成",
                    "✓ 置信度：85%"
                ]
            }
        }
    ],
    "code": [
        {
            "id": 1,
            "title": "代码分析",
            "description": "分析代码结构和质量",
            "icon": "fas fa-code",
            "status": "completed",
            "details": {
                "title": "代码分析完成",
                "items": [
                    "✓ 语法分析：完成",
                    "✓ 结构分析：完成",
                    "✓ 复杂度评估：中等",
                    "✓ 质量评分：85分"
                ]
            }
        }
    ]
}


@router.get("/config/{conversation_type}", response_model=List[TaskConfig])
async def get_processing_config(conversation_type: str):
    """获取处理任务配置"""
    try:
        if conversation_type not in task_configs:
            raise HTTPException(status_code=404, detail="未找到对应的处理配置")
        
        configs = task_configs[conversation_type]
        return [TaskConfig(**config) for config in configs]
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/tasks/{conversation_type}", response_model=ProcessingResponse)
async def get_processing_tasks(conversation_type: str):
    """获取处理任务"""
    try:
        if conversation_type not in task_configs:
            raise HTTPException(status_code=404, detail="未找到对应的处理任务")
        
        configs = task_configs[conversation_type]
        tasks = [ProcessingTask(**config) for config in configs]
        
        return ProcessingResponse(
            success=True,
            data=tasks,
            message="获取处理任务成功",
            timestamp=datetime.now()
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))